import { PageContainer } from '@ant-design/pro-components';
import React, { useEffect, useState } from "react";
import { api } from "@/utils/api";
import { Card, List, message, Modal, Pagination } from "antd";
import './index.less';

const HomePage: React.FC = () => {
  const [ messageApi, contextHolder ] = message.useMessage();
  const [ loading, setLoading ] = useState(false)
  const [ pagination, setPagination ] = useState({page: 1, total: 0})
  const [ creatives, setCreatives ] = useState([])

  const [ selectedCreative, setSelectedCreative ] = useState(null);
  const [ isModalVisible, setIsModalVisible ] = useState(false);

  const handleViewCreative = (item: any) => {
    setSelectedCreative(item);
    setIsModalVisible(true);
  };

  useEffect( () => {
    setLoading(true);

    (async () => {
      try {
        let data = await api(`creative/exhibition?page=${pagination.page}`)
        setPagination({ ...pagination, total: data.total })
        setCreatives(data.data)
      } catch (error: any) {
        messageApi.open({
          type: 'error',
          content: `获取创意展览列表失败: ${error.message}`,
        });
        console.error(error)
      } finally {
        setLoading(false);
      }
    })();
  }, [pagination.page])

  return (
    <PageContainer ghost loading={ loading }>
      { contextHolder }
      <div className="exhibition-container">
        <div className="content">
          <Pagination align="center" current={ pagination.page } total={ pagination.total } pageSize={ 12 }
                      onChange={ (page) => setPagination({ page, total: pagination.total }) }/>
          <div style={ { height: 20 } }></div>
          <List
            grid={ { gutter: 16, column: 4 } }
            dataSource={ creatives }
            renderItem={ (item) => (
              <List.Item>
                <Card
                  cover={ <img alt={ item?.task?.prompt } src={ item?.thumb_path }/> }
                  onClick={ () => handleViewCreative(item) }
                >
                  <Card.Meta title={ item?.task?.prompt }/>
                </Card>
              </List.Item>
            ) }
          />
        </div>

        <Modal
          width={ 720 }
          closable={ false }
          style={ { top: 10 } }
          title={ "" }
          visible={ isModalVisible }
          footer={ [] }
          onCancel={ () => setIsModalVisible(false) }
        >
          <div className="modal-content">
            <img className="modal-image" style={ { maxWidth: '100%' } }
                 src={ isModalVisible ? selectedCreative?.image_path : "" } alt={ selectedCreative?.image_path }/>
            <div style={ { height: 10 } }></div>
            <div className="modal-info">
              <h3>提示词</h3>
              <p>{ selectedCreative?.task?.prompt }</p>
            </div>
          </div>
        </Modal>
      </div>
    </PageContainer>
  );
};

export default HomePage;
